package NG::Sys::Loop::Cron;
use strict;
use warnings;
use utf8;

use base 'NG::Sys::Loop::Run';

use NG::Sys::File;

sub on_before_loop {
	my ($self) = @_;
	$self->SUPER::on_before_loop;
	$self->warn_to_logger;
	$self->ext_die;
	if(my $pid = $self->can_run){
		die "Another process runing($pid)\n";
	}
	$self->write_pid;
	return 1;
}
sub on_after_loop {
	my ($self,$error) = @_;
	$self->delete_pid;
}

sub read_pid {
	my ($self) = @_;
	return ( -s $self->pidfile ) ? read_int($self->pidfile) : 0;
}

sub write_pid {
	my ($self) = @_;
	write_int($self->pidfile,$$);
	chmod 0666, $self->pidfile;
}

sub delete_pid {
	my ($self) = @_;
	unlink $self->pidfile;
}

sub can_run {
	my ($self) = @_;
	if ( my $pid = $self->read_pid ) {
		if(my $run = is_proc_run($pid,$self->script)){
			return $pid;
		}
	}
	return 0;
}
sub pidfile {
	my ($self) = @_;
	$self->{cfg}{path}{var}."/".$self->script.".pid";
}

1;
